package com.ttmusic.view;

import java.util.Timer;
import java.util.TimerTask;

import com.ttmusic.activitys.R;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

/**
 * 自定义正在加载dialog
 * @author Administrator
 *
 */
public class LoadingDialog extends Dialog{
	
	private Context context;
	private boolean isLoading = true;
	private int i = 0;
	private ImageView searchLoading;
	private Timer loadingTimer;

	public LoadingDialog(Context context) {
		super(context, R.style.dialog_noborder);
		this.context = context;
	}
	
	private Handler loadingHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(isLoading) {
				switch (i) {
					case 0:searchLoading.setImageResource(R.drawable.loading_0);break;
					case 1:searchLoading.setImageResource(R.drawable.loading_1);break;
					case 2:searchLoading.setImageResource(R.drawable.loading_2);break;
					case 3:searchLoading.setImageResource(R.drawable.loading_3);break;
					case 4:searchLoading.setImageResource(R.drawable.loading_4);break;
					case 5:searchLoading.setImageResource(R.drawable.loading_5);break;
					case 6:searchLoading.setImageResource(R.drawable.loading_6);break;
					case 7:searchLoading.setImageResource(R.drawable.loading_7);break;
					default:break;
				}
				i++;
				if(i == 7) {i = 0;}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		loadingTimer = new Timer();
	    View view = LayoutInflater.from(context).inflate(R.layout.dialog_search_loadprogress, null);
	    searchLoading = (ImageView)view.findViewById(R.id.searchLoading);
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    this.setContentView(view);
    	//设置点击旁边地方时不能关闭它 只有当加载完成或者加载失败才关闭它
	    this.setCancelable(false);
	}

	@Override
	public void show() {
		isLoading = true;
		super.show();
		loadingTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				if(isLoading && null != loadingHandler)
					loadingHandler.sendMessage(loadingHandler.obtainMessage());
			}
		}, 0, 100);
	}

	@Override
	public void dismiss() {
		isLoading = false;
		loadingTimer.purge();
		super.dismiss();
	}

	
	
	
}
